package com.taglab.chic.search;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;

/**
 * @author Markus Kobler
 */
public class SpringSearchController extends AbstractController {

  private final static Logger logger = LoggerFactory.getLogger(SpringSearchController.class);

  public final static String DEFAULT_SEARCH_QUERY_PARAM = "q";
  public final static String DEFAULT_SEARCH_PAGE_PARAM  = "p";
  public final static String DEFAULT_SEARCH_WIDTH_PARAM = "c";

  private SearchService searchService;
  
  private String searchQueryParam = DEFAULT_SEARCH_QUERY_PARAM;
  private String searchPageParam = DEFAULT_SEARCH_PAGE_PARAM;
  private String searchCountParam = DEFAULT_SEARCH_WIDTH_PARAM;

  private int defaultCount = 10;

  private String viewName = "search";

  private String resultsKey = "searchResults";

  @Resource
  public void setSearchService(SearchService searchService) {
    this.searchService = searchService;
  }

  public void setSearchQueryParam(String searchQueryParam) {
    this.searchQueryParam = searchQueryParam;
  }

  public void setSearchPageParam(String searchIndexParam) {
    this.searchPageParam = searchIndexParam;
  }

  public void setSearchCountParam(String searchCountParam) {
    this.searchCountParam = searchCountParam;
  }

  public void setDefaultCount(int defaultCount) {
    this.defaultCount = defaultCount;
  }

  public String getViewName() {
    return viewName;
  }

  public void setViewName(String viewName) {
    this.viewName = viewName;
  }

  public String getResultsKey() {
    return resultsKey;
  }

  public void setResultsKey(String resultsKey) {
    this.resultsKey = resultsKey;
  }

  protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Query query = parseSearchQuery(request);
    
    logger.debug("search query {}", query);

    SearchResults results = searchService.search(query);

    logger.debug("{} returned {}", query, results);

    return new ModelAndView(getViewName(), getResultsKey(), results);
  }


  protected Query parseSearchQuery(HttpServletRequest request) {
    Query query = new Query(request.getParameter(searchQueryParam));
    query.setStartPage(parseParamAsInt(request, searchPageParam, 1));
    query.setCount(parseParamAsInt(request, searchCountParam, defaultCount));
    return query;
  }
  
  
  private int parseParamAsInt(HttpServletRequest request, String param, int defaultValue) {
    String value = request.getParameter(param);
    if( value != null ) {
      try {
        return Integer.parseInt(value);
      } catch( NumberFormatException ex ) {
        logger.debug("Failed to parse '{}'", value);
      }
    }
    return defaultValue;
  }

}
